package com.jarvis.app.car;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.track.TraceAnimationListener;
import com.baidu.mapapi.map.track.TraceOptions;
import com.baidu.mapapi.model.LatLng;
import com.jarvis.app.car.common.MessageResult;
import com.jarvis.app.car.dto.JlAndTimeDto;
import com.jarvis.app.car.model.Car;
import com.jarvis.app.car.model.CarTrack;
import com.jarvis.app.car.util.BaiDuMapUtils;
import com.jarvis.app.car.util.ServiceManager;
import com.jarvis.app.car.util.ThreadPoolManager;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class CarTrackActivity extends AppCompatActivity {

    private Toolbar toolbar;

    private MapView mMapView;

    private Button bt_search;

    private EditText et_endTime;

    private EditText et_startTime;

    private BaiduMap mBaiDuMap;

    private final Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<List<CarTrack>> messageResult = (MessageResult<List<CarTrack>>) message.obj;
            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(CarTrackActivity.this, messageResult.getMsg(), Toast.LENGTH_SHORT).show();

            } else {
                List<CarTrack> result = messageResult.getResult();
                if (result == null || result.size() <= 0) {
                    Toast.makeText(CarTrackActivity.this, "暂无轨迹信息", Toast.LENGTH_SHORT).show();

                } else {
                    //地图定位显示
                    MapStatusUpdate status2 = MapStatusUpdateFactory.newLatLng(getTraceLocation(result).get(0));
                    mBaiDuMap.setMapStatus(status2);

                    //显示比例大小
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.zoom(18.0f);
                    mBaiDuMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                    // 创建轨迹对象
                    TraceOptions traceOptions = new TraceOptions();
                    traceOptions.animationTime(5000);
                    traceOptions.animate(true);
                    traceOptions.animationType(TraceOptions.TraceAnimateType.TraceOverlayAnimationEasingCurveLinear);
                    traceOptions.color(0xAAFF0000);
                    traceOptions.width(10);
                    traceOptions.points(getTraceLocation(result));

                    // 创建图标
                    BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.car);
                    // 设置轨迹动画图标并让图标平滑移动
                    traceOptions.icon(bitmap).setPointMove(true);


                    final JlAndTimeDto jlAndTimeDto = new JlAndTimeDto();
                    double lucheng = 0;

                    for (int i = 0; i < result.size(); i++) {
                        CarTrack carTrack = result.get(i);
                        int j = i+1;
                        CarTrack carTrack1 = result.get(Math.min(j, result.size() - 1));
                        lucheng = lucheng + BaiDuMapUtils.GetDistance(
                                Double.valueOf(carTrack.getX_point()),
                                Double.valueOf(carTrack.getY_point()),
                                Double.valueOf(carTrack1.getX_point()),
                                Double.valueOf(carTrack1.getY_point())
                        );
                    }

                    jlAndTimeDto.setJuli(new DecimalFormat("##0.0").format(lucheng).toString());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        jlAndTimeDto.setTime(ChronoUnit.MINUTES.between(result.get(0).getCreateTime(), result.get(result.size() - 1).getCreateTime()));
                    }


                    mBaiDuMap.addTraceOverlay(traceOptions, new TraceAnimationListener() {
                        @Override
                        public void onTraceAnimationUpdate(int percent) {
                            // 轨迹动画更新进度回调
                        }

                        @Override
                        public void onTraceUpdatePosition(LatLng position) {
                            // 轨迹动画更新的当前位置点回调
                        }

                        @Override
                        public void onTraceAnimationFinish() {
                            // 轨迹动画结束回调
                            new AlertDialog.Builder(CarTrackActivity.this)
                                    .setTitle("温馨提示！")
                                    .setMessage("行驶时间: " + jlAndTimeDto.getTime() + "分，行驶距离："+jlAndTimeDto.getJuli()+"米")

                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .show();


                        }
                    });
                }


            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_car_track);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        toolbar = findViewById(R.id.toolbar);
        mMapView = (MapView) findViewById(R.id.bmapView);
        bt_search = findViewById(R.id.bt_search);
        et_endTime = findViewById(R.id.et_endTime);
        et_startTime = findViewById(R.id.et_startTime);
        mBaiDuMap = mMapView.getMap();


        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = getIntent();
                long carId = intent.getLongExtra("carId", 0);

                String endTime = et_endTime.getText().toString();
                String startTime = et_startTime.getText().toString();

                if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
                    Toast.makeText(CarTrackActivity.this, "开始时间/结束时间不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        MessageResult<List<CarTrack>> messageResult = ServiceManager.carTrackService.list(carId, startTime, endTime);
                        Message msg = Message.obtain();
                        msg.obj = messageResult;
                        handler.sendMessage(msg);
                    }
                });

            }
        });

        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }


    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }


    private List<LatLng> getTraceLocation(List<CarTrack> result) {
        List<LatLng> lists = new ArrayList<>();
        for (CarTrack carTrack : result) {
            lists.add(new LatLng(Double.valueOf(carTrack.getX_point()), Double.valueOf(carTrack.getY_point())));
        }

        return lists;

    }
}